from rest_framework import serializers
from certificate_manager.models import User, Department, DepartRestrict
from django.contrib.auth import authenticate

class NestedJoin(serializers.Serializer):
        restrict = serializers.PrimaryKeyRelatedField(queryset=DepartRestrict.objects.all(), required=True)
        uid = serializers.CharField(max_length=20, required=True)
        play_role_imp = serializers.IntegerField()
        
        def validate(self, attrs):
                user = User.objects.get(uid=attrs['uid'])
                restrict = attrs['restrict']

                if restrict.department != user.department:
                    raise serializers.ValidationError('user not fufill restrict, uid: ' + user.uid)

                return attrs
                
        # 给定一个用户 需要将其序列化
        def to_representation(self, join):
                return {
                        'restrict_type': join.restrict.restrict_type, # 最方便的方式就是通过这里进行展示
                        'restrict_id': join.restrict.pk,
                        'uid': join.user.uid,
                        'name': join.user.name,
                        'head': join.user.head,
                        'play_role_imp': join.play_role_imp,
                        'status': join.status,
                        'msg': join.msg,
                        'date': join.acc_date
                }
